package cn.how2go.net.server.protocol;

import cn.how2go.net.server.base.SessionData;
import cn.how2go.net.server.util.BinaryUtil;

/**
 * Created by Administrator on 2018/4/19.
 */
public class JTFactory {

    public static byte[] getJTBytes(MessageType type, JTMessage responseMessage, String simno){
        return JTFactory.getJTBytes(type,false,false,simno,responseMessage);
    }

    public static byte[] getJTBytes(MessageType type, boolean packages, boolean rsa, String simno, JTMessage responseMessage){
        byte[] response = null;
        JTHeader responseHeader = new JTHeader();
        //回复的总报文
        JTBytes responseByte = new JTBytes();
        //编码计算crc
        byte crcByte;
        //组报文头
        responseHeader.setMsgType((short) type.getId());
        responseHeader.setMessage(JTFactory.getMessage(responseMessage.getBodyLength(),packages,rsa));
        responseHeader.setSimno(simno);
        responseHeader.setSeriaNo(SessionData.SERIALNUMBER++);
        responseByte.setHeader(responseHeader);
        responseByte.setBody(responseMessage.write());
        response = responseByte.writeBody();
        //重新计算CRC校验码
        crcByte = BinaryUtil.GetCheckXor(response,0,response.length);
        responseByte.setCrc(crcByte);
        responseByte.setPrefix((byte) 0x7e);
        responseByte.setEndfix((byte) 0x7e);
        return responseByte.write();
    }

    /**
     * 计算长度字节体
     * @param length
     * @param packages
     * @param rsa
     * @return
     */
    public static short getMessage(short length,boolean packages,boolean rsa){
        if(packages){
            length |= 0x2000;
        }
        if(rsa){
            length |= 0x400;
        }
        return length;
    }

    public static void main(String[] args) {
        JT_0001 jt_0001 = new JT_0001();
        jt_0001.setSeriaNo((short) 0x0002);
        jt_0001.setMsgType((short) 0x62);
        jt_0001.setResult((byte) 0x01);
        byte[] response = JTFactory.getJTBytes(MessageType.JT_0001, jt_0001,"13625190030");
        System.out.println(BinaryUtil.ToHexFormatString(response));
    }

}
